package com.karrysong.blog_springboot.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.karrysong.blog_springboot.entity.Article;
import com.karrysong.blog_springboot.entity.Category;
import com.karrysong.blog_springboot.entity.Comment;
import com.karrysong.blog_springboot.entity.Tag;
import com.karrysong.blog_springboot.enums.ErrorCode;
import com.karrysong.blog_springboot.mapper.ArticleMapper;
import com.karrysong.blog_springboot.mapper.CategoryMapper;
import com.karrysong.blog_springboot.service.CategoryService;
import com.karrysong.blog_springboot.vo.CategoryVo;
import com.karrysong.blog_springboot.vo.CommentVo;
import com.karrysong.blog_springboot.vo.Result;
import com.karrysong.blog_springboot.vo.params.CategoryPage;
import com.karrysong.blog_springboot.vo.params.CategoryParam;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: CategoryService
 * @Author: KarrySong
 * @Date: 2022/8/5 9:18
 * @Description:
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public CategoryVo findCategoryById(Long id){
        Category category = categoryMapper.selectById(id);

        CategoryVo categoryVo = new CategoryVo();
        if (category != null){
            BeanUtils.copyProperties(category,categoryVo);
            System.out.println("id:" + id + "  == " + category);
        }else {
            System.out.println("--------------------------------------------------------------------------");
        }
        return categoryVo;
    }

    @Override
    public Result getCategories(CategoryPage categoryPage) {
        Page<Category> page = new Page<>(categoryPage.getPage(), categoryPage.getPageSize());
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Strings.isNotEmpty(categoryPage.getCategoryName()), Category::getCategoryName, categoryPage.getCategoryName());
        IPage<Category> pageResult = categoryMapper.selectPage(page, wrapper);
        List<Category> records = pageResult.getRecords();
        List<CategoryVo> articleVoList = copyList(records);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("categoryList", articleVoList);
        jsonObject.put("pageData", pageResult);
        return Result.success(jsonObject);
    }

    @Override
    public Result updateCategory(CategoryParam categoryParam) {

        //判断是否重复
        LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();
        categoryWrapper.eq(Strings.isNotEmpty(categoryParam.getCategoryName()), Category::getCategoryName, categoryParam.getCategoryName());
        categoryWrapper.or();
        categoryWrapper.eq(Strings.isNotEmpty(categoryParam.getDescription()), Category::getDescription, categoryParam.getDescription());
        List<Category> categories = categoryMapper.selectList(categoryWrapper);
        if (categories != null && categories.size() > 0){
            //重复
            return  Result.fail(ErrorCode.ADMIN_ERROR, "信息重复");
        }

        Category category = new Category();
        category.setId(categoryParam.getId());
        if (categoryParam.getCategoryName() != null){
            category.setCategoryName(categoryParam.getCategoryName());
        }
        if (categoryParam.getDescription() != null){
            category.setDescription(categoryParam.getDescription());
        }
        if (categoryParam.getAvatar() != null){
            category.setAvatar(categoryParam.getAvatar());
        }
        int i = categoryMapper.updateById(category);
        if (i > 0){
            return Result.success(null);
        }else {
            return Result.fail(ErrorCode.ADMIN_ERROR, "修改类型失败");
        }

    }

    @Override
    public Result addCategory(CategoryParam categoryParam) {
        //判断是否重复
        LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();
        categoryWrapper.eq(Strings.isNotEmpty(categoryParam.getCategoryName()), Category::getCategoryName, categoryParam.getCategoryName());
        categoryWrapper.or();
        categoryWrapper.eq(Strings.isNotEmpty(categoryParam.getDescription()), Category::getDescription, categoryParam.getDescription());
        List<Category> categories = categoryMapper.selectList(categoryWrapper);
        if (categories != null && categories.size() > 0){
            //重复
            return  Result.fail(ErrorCode.ADMIN_ERROR, "信息重复");
        }

        Category category = new Category();
        if (categoryParam.getCategoryName() != null){
            category.setCategoryName(categoryParam.getCategoryName());
        }
        if (categoryParam.getDescription() != null){
            category.setDescription(categoryParam.getDescription());
        }
        if (categoryParam.getAvatar() != null){
            category.setAvatar(categoryParam.getAvatar());
        }
        int i = categoryMapper.insert(category);
        if (i > 0){
            return Result.success(null);
        }else {
            return Result.fail(ErrorCode.ADMIN_ERROR, "添加类型失败");
        }
    }

    @Override
    public Result deleteCategory(Long id) {
        //删除前考虑所属文章，如果没有则直接删除
        LambdaQueryWrapper<Article> articleWrapper = new LambdaQueryWrapper<>();
        articleWrapper.eq(Article::getCategoryId, id);
        List<Article> articleList = articleMapper.selectList(articleWrapper);
        int res = -1;
        if (articleList != null && articleList.size() > 0){
            //有文章，判断是否有“其他”类型，如果有直接修改，否则先创建“其他”
            LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();
            categoryWrapper.eq(Category::getCategoryName, "其他");
            List<Category> categories = categoryMapper.selectList(categoryWrapper);
            Long newCategoryId = null;
            if (categories == null || categories.size() <= 0){
                //不存在“其他”，创建“其他”
                Category category = new Category();
                category.setCategoryName("其他");
                category.setDescription("其他文章");
                //category.setAvatar("http://asduhiuhdisa.sad");
                categoryMapper.insert(category);
                newCategoryId = category.getId();
            }else {
                newCategoryId = categories.get(0).getId();

                //特殊情况，删除的是“其他”，禁止
                if (newCategoryId.equals(id)){
                    return Result.fail(ErrorCode.ADMIN_ERROR, "禁止删除‘其他’类型");
                }

            }
            //修改该类型下文章id
            for (Article article : articleList) {
                article.setCategoryId(newCategoryId);
                articleMapper.updateById(article);
            }
        }

        res = categoryMapper.deleteById(id);

        if (res > 0){
            return Result.success(null);
        }else {
            return Result.fail(ErrorCode.ADMIN_ERROR, "删除类型失败");
        }
    }

    @Override
    public Result deleteCategoryList(Long[] arr) {
        if (arr == null || arr.length <= 0){
            return Result.fail(ErrorCode.ADMIN_ERROR.getCode(), "批量删除数据为空");
        }
        int success = 0, fail = 0;
        for (Long aLong : arr) {
            Result result = deleteCategory(aLong);
            if (result.isSuccess()){
                success++;
            }else {
                fail++;
            }
        }
        if (success == 0){
            return Result.fail(ErrorCode.ADMIN_ERROR, "批量删除失败");
        }else if (fail == 0){
            return Result.success(null);
        }else {
            return Result.fail(ErrorCode.ADMIN_ERROR, "批量删除部分失败");
        }
    }

    //@Override
    public CategoryVo copy(Category category){
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category,categoryVo);
        return categoryVo;
    }

    //@Override
    public List<CategoryVo> copyList(List<Category> categoryList){
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (Category category : categoryList) {
            categoryVoList.add(copy(category));
        }
        return categoryVoList;
    }

    @Override
    public Result findAll() {
        List<Category> categories = categoryMapper.selectList(new LambdaQueryWrapper<>());
        return Result.success(copyList(categories));
    }

}
